package com.jqh.jqhmusic;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

import com.jqh.myplayer.MuteEnum;
import com.jqh.myplayer.TimeInfo;
import com.jqh.myplayer.listener.OnCompleteListener;
import com.jqh.myplayer.listener.OnErrorListener;
import com.jqh.myplayer.listener.OnLoadListener;
import com.jqh.myplayer.listener.OnParparedListener;
import com.jqh.myplayer.listener.OnPauseResumeListener;
import com.jqh.myplayer.listener.OnTimeInfoListener;
import com.jqh.myplayer.listener.OnValumeDBListener;
import com.jqh.myplayer.log.JqhLog;
import com.jqh.myplayer.player.JqhPlayer;

import java.io.File;

public class MainActivity extends AppCompatActivity {



    private JqhPlayer jqhPlayer;
    public static final int PLAY_STATUS_NOSTART = 0 ;
    public static final int PLAY_STATUS_PAUSE = 1 ;
    public static final int PLAY_STATUS_PLAYING = 2 ;
    private int playStatus = PLAY_STATUS_NOSTART;
    private Button playBtn;
    private TextView textView;
    private TextView playInfoTextView;
    private TextView playStatusTextView;
    private SeekBar seekSeekBar, seekBarVolume;
    private boolean isSeekBar = false;
    private int position = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        playBtn = findViewById(R.id.playbtn);
        textView = findViewById(R.id.time_tv);
        playInfoTextView = findViewById(R.id.play_info_tv);
        playStatusTextView = findViewById(R.id.play_status_tv);
        seekSeekBar = findViewById(R.id.seekbar_view);
        seekBarVolume = findViewById(R.id.volumebar_view);
        jqhPlayer = new JqhPlayer();

        seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                jqhPlayer.setVolume(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        seekSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (jqhPlayer.getDuration() > 0 && isSeekBar) {
                    position = jqhPlayer.getDuration() * progress / 100;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBar = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                jqhPlayer.seek(position);
                isSeekBar = false;
            }
        });
        jqhPlayer.setOnParparedListener(new OnParparedListener() {
            @Override
            public void onParpared() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JqhLog.d("perpared");
                        jqhPlayer.start();
                        playBtn.setText("播放");
                        playStatus = PLAY_STATUS_PLAYING;
                    }
                });

            }
        });

        jqhPlayer.setOnLoadListener(new OnLoadListener() {
            @Override
            public void onLoad(final Boolean load) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (load) {
                            JqhLog.d("加载中...");
                            playStatusTextView.setText("加载中...");
                        } else {
                            JqhLog.d("播放中...");
                            playStatusTextView.setText("播放中...");
                        }
                    }
                });

            }
        });

        jqhPlayer.setOnPauseResumeListener(new OnPauseResumeListener() {
            @Override
            public void onPause(boolean pause) {
                if (pause) {
                    playStatus = PLAY_STATUS_PAUSE;
                    playBtn.setText("播放");
                } else {
                    playStatus = PLAY_STATUS_PLAYING;
                    playBtn.setText("暂停");
                }
            }
        });

        jqhPlayer.setOnTimeInfoListener(new OnTimeInfoListener() {
            @Override
            public void onTimeInfo(TimeInfo timeInfo) {
                JqhLog.d("timeinfo " + timeInfo.toString());
                Message message = Message.obtain();
                message.what = 1;
                message.obj = timeInfo;
                handler.sendMessage(message);
            }
        });

        jqhPlayer.setOnErrorListener(new OnErrorListener() {
            @Override
            public void onError(final int code, final String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        playInfoTextView.setText(msg + " #" + code);
                    }
                });

            }
        });

        jqhPlayer.setOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        playInfoTextView.setText("已播放完成");
                    }
                });
            }
        });

        jqhPlayer.setOnValumeDBListener(new OnValumeDBListener() {
            @Override
            public void onDBValue(int db) {
                JqhLog.d("onDBValue" + db);
            }
        });

    }

    public void begin(View view) {
        String file = getDiskCachePath(this) + "/qingren.avi";
//        Log.d("file", file);
//        jqhPlayer.setSource(file);

        if(playStatus == PLAY_STATUS_NOSTART) {
            JqhLog.d("java perpare");
            jqhPlayer.setSource("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
//            jqhPlayer.setSource("https://www.qianxueyunke.com/qingren.avi");
//            jqhPlayer.setSource(file);
            jqhPlayer.parpared();
            playStatus = PLAY_STATUS_PLAYING;
        } else if (playStatus == PLAY_STATUS_PAUSE) {
            // 调用继续播放
            playStatus = PLAY_STATUS_PLAYING;
            jqhPlayer.resume();
            JqhLog.d("java resume");
        } else if (playStatus == PLAY_STATUS_PLAYING) {
            // 调用暂停播放
            playStatus = PLAY_STATUS_PAUSE;
            jqhPlayer.pause();
            JqhLog.d("java pause");
        }

    }

    public void playpcm(View view) {
        String pcmFile = getDiskCachePath(this) + "/qingren.pcm";
        jqhPlayer.n_playpcm(pcmFile);
    }

    public String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if(sdCardExist)
        {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    public static String getDiskCachePath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            return context.getExternalCacheDir().getPath();
        } else {
            return context.getCacheDir().getPath();
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (!isSeekBar) {
                    TimeInfo timeInfo = (TimeInfo)msg.obj;
//                String cur = TimeUtils.formatDateTime(timeInfo.getCurrentTime());
//                String total = TimeUtils.formatDateTime(timeInfo.getTotalTime());
                    textView.setText(timeInfo.getCurrentTime() + "-" + timeInfo.getTotalTime());
                    seekSeekBar.setProgress(timeInfo.getCurrentTime() * 100 / timeInfo.getTotalTime());
                }

            }
        }
    };

    public void stopPlay(View view) {
        if (playStatus != PLAY_STATUS_NOSTART) {
            jqhPlayer.stop();
            playStatus = PLAY_STATUS_NOSTART;
            playBtn.setText("开始");
        }
    }

    public void seekClick(View view) {
        jqhPlayer.seek(50);
    }

    public void playNext(View view) {
        if(jqhPlayer != null) {
            String file = getDiskCachePath(this) + "/qingren.avi";
            jqhPlayer.playNext(file);
        }
    }

    public void leftClick(View view) {
        jqhPlayer.setMute(MuteEnum.MUTE_LEFT);
    }

    public void rightClick(View view) {
        jqhPlayer.setMute(MuteEnum.MUTE_RIGHT);
    }

    public void centerClick(View view) {
        jqhPlayer.setMute(MuteEnum.MUTE_CENTER);
    }

    public void speed(View view) {
        jqhPlayer.setSpeed(1.5f);
        jqhPlayer.setPitch(1.0f);
    }

    public void pitch(View view) {
        jqhPlayer.setSpeed(1.0f);
        jqhPlayer.setPitch(1.5f);
    }

    public void speedPitch(View view) {
        jqhPlayer.setSpeed(1.5f);
        jqhPlayer.setPitch(1.5f);
    }

    public void normalPlay(View view) {
        jqhPlayer.setSpeed(1.0f);
        jqhPlayer.setPitch(1.0f);
    }


    public void recodStartClick(View view) {
        String file = getDiskCachePath(this) + "/outputaac.aac";
        jqhPlayer.startRecod(new File(file));
    }

    public void recodPauseClick(View view) {
        jqhPlayer.pauseRecord();
    }

    public void recodResumeClick(View view) {
        jqhPlayer.resumeRecord();
    }

    public void recodStopClick(View view) {
        jqhPlayer.stopRecord();
    }
}
